package com.mobile.struts.action;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mobile.business.grid.IBaseBusiness;
import com.mobile.gridUtil.FilterBean;
import com.mobile.gridUtil.ParseFilterData;
import com.mobile.struts.action.tools.AssociateTableInfo;
import com.mobile.struts.action.tools.ClassDelegate;
import com.mobile.tools.BeanUtil;
import com.mobile.tools.JsonHelp;
import com.mobile.tools.POIExcel;
import com.mobile.tools.PageBean;

public class GridBaseAction extends BaseDispatchAction {
	private final Logger LOGGER = LogManager.getLogger(GridBaseAction.class);
	
	
	protected JsonHelp jsonHelp=new JsonHelp();
	
	private IBaseBusiness getBusinessBean(){
		return (IBaseBusiness)getWac().getBean(IBaseBusiness.BEAN_ID);
	}
	/**
	 * 通过ajax在后台读取数据
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward ajaxList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {		
		Map<String,FilterBean> map=createFilterMap(request);		
		/*String deptId="deptId";
		String userId="userId";*/
		/*templeteManageForm.setDeptId(deptId);
		templeteManageForm.setUserId(userId);*/
		
		String startStr=request.getParameter("start");
		String limit=request.getParameter("limit");
		
		String clazz = request.getParameter("clazz");
		clazz=ClassDelegate.clazzMap.get(clazz);
		String obj = request.getParameter("obj"); 
		//关联表信息
		String associated = request.getParameter("associated");
		
		int start=0;
		int pageSize=10;
		if(startStr!=null&&!startStr.equals("0")&&limit!=null){
			pageSize=Integer.valueOf(limit);
			int temp=Integer.valueOf(startStr)/pageSize;
			start=temp+1;
		}
		PrintWriter out=null;
		
		try {
			
			Object pojo=Class.forName(clazz).newInstance();
			if(obj!=null&&obj.length()!=0){
				jsonHelp.parseJson(obj,pojo);
			}
			List<AssociateTableInfo> list = new ArrayList<AssociateTableInfo>();
			/*
			 *判断是否有关联的表 
			 */
			if(associated!=null&&associated.length()!=0){
				
				list = jsonHelp.parseJsonArray(associated);
				BeanUtil.copyProperties(pojo, list);
			}
			PageBean pb=null;
			if(list.isEmpty()){
				pb=getBusinessBean()
						.getPageBean(start,pageSize,pojo,map);
			}else{
				pb=getBusinessBean()
						.getPageBean(start,pageSize,pojo,map,list);
			}
					
			out=response.getWriter();
			StringBuffer content=new StringBuffer();
			content.append("{'results':"+pb.getTotalSize()+",");
			content.append("'rows':"+
					jsonHelp
						.getJson(pb
								.getList())+"}");
			out.println(content);
		} catch(Exception e){
			e.printStackTrace();
			LOGGER.info(e);
		}finally{		
			out.close();
		}	
		return null;
	}
	/**
	 * 通过ajax发送要冻结的数据的id到后台
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward ajaxComboList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out=null;
		
		String clazz = request.getParameter("clazz");
		clazz=ClassDelegate.clazzMap.get(clazz);
		String obj = request.getParameter("obj"); 
		
		try {
			Object pojo=Class.forName(clazz).newInstance();
			if(obj!=null&&obj.length()!=0){
				jsonHelp.parseJson(obj,pojo);
			}
			List list=getBusinessBean().findByExample(pojo);			
			out=response.getWriter();
			StringBuffer content=new StringBuffer();
			content.append(jsonHelp.getJson(list ));
			System.out.println(content);
			out.println(content);
		} catch(Exception e){
			e.printStackTrace();
		}finally{		
			out.close();
		}	
		return null;
	}
	/**
	 * 创建FilterMap用于查询
	 * @param request			请求变量
	 * @return
	 */
	public Map<String,FilterBean> createFilterMap(HttpServletRequest request){
		Enumeration enu= request.getParameterNames();
		Map<String,FilterBean> map=new HashMap<String,FilterBean>();
		/*
		 * 解析request里面的数据
		 */
		try {
			while(enu.hasMoreElements()){
				String name=(String)enu.nextElement();
				if(name.contains("filter")){
					/*
					 * 解析request中的name
					 */
					String[] array=ParseFilterData.parse(name);
					String value=request.getParameter(name);
					FilterBean filterBean=null;
					/*
					 * map中的键 
					 */
					String key=array[0];
					/*
					 * 如果map中有key键则读取出键值，如果没有则创建一个
					 */
					if(map.containsKey(key)){
						filterBean=map.get(key);
						PropertyDescriptor pd=new PropertyDescriptor(array[1],filterBean.getClass());
						pd.getWriteMethod().invoke(filterBean,value );
					}else{
						filterBean=new FilterBean();
						PropertyDescriptor pd=new PropertyDescriptor(array[1],filterBean.getClass());
						pd.getWriteMethod().invoke(filterBean,value );
						map.put(key, filterBean);
					}
				}
			}
		} catch (IntrospectionException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalAccessException e){
			e.printStackTrace();
		} catch (InvocationTargetException e){
			e.printStackTrace();
		}
		
		return map;
	}
	/**
	 * 显示要编辑的数据
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward ajaxEdit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {		
		String uniqueCode=request.getParameter("uniqueCode");
				
		//不包含的字段
		String excFields = request.getParameter("excFields");
		
		String clazz = request.getParameter("clazz");
		clazz=ClassDelegate.clazzMap.get(clazz);
		
			
		PrintWriter out=null;
		try {
			
			if(clazz==null||"".equals(clazz)){
				out.println(jsonHelp.getFormFailJson("操作失败，请联系管理员！"));
				return null;
			}
			
			Object pojo=Class.forName(clazz).newInstance();
			
			pojo=(Object)getBusinessBean().findById(pojo.getClass(),uniqueCode);
			out=response.getWriter();
			
			String content = jsonHelp.getFormSuccessJsonExceptFields(pojo, excFields);
			out.println(content);
		} catch(NullPointerException e){
			//e.printStackTrace();
			out.println(jsonHelp.getFormFailJson("找不到您点击的菜单信息！"));
		} catch(Exception e){
			e.printStackTrace();
		} finally{		
			out.close();
		}
		return null;
	}
	/**
	 * 发送数据到后台并保存
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return		
	 */
	public ActionForward ajaxSave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String deptId="deptId";
		String userId="userId";
		
		String uniqueCode=request.getParameter("uniqueCode");
		
		String clazz = request.getParameter("clazz");
		clazz=ClassDelegate.clazzMap.get(clazz);
		if(clazz==null||"".equals(clazz)){
			return null;
		}
		
		try {
			Object pojo=Class.forName(clazz).newInstance();
			BeanUtil.populate(pojo, request.getParameterMap());
			
			if(uniqueCode==null||"".equals(uniqueCode)){
				getBusinessBean().save(pojo);
			}else{
				getBusinessBean().mergeNotNull(uniqueCode,pojo);
			}
			
			//getBusinessBean().merge(pojo);
		} catch(Exception e){
			PrintWriter out=null;
			try {				
				out=response.getWriter();
				out.println(JsonHelp.getFormFailJson("保存数据失败！"));
				e.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} finally{
				out.close();
			}
		}
		return null;	
	}
	/**
	 * 删除数据
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return		
	 */
	public ActionForward ajaxDelete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String deptId="deptId";
		String userId="userId";
		
		String uniqueCodes=request.getParameter("uniqueCodes");
		String[] uniqueCodeArray=uniqueCodes.split(",");
		
		String clazz = request.getParameter("clazz");
		clazz=ClassDelegate.clazzMap.get(clazz);
		if(clazz==null||"".equals(clazz)){
			return null;
		}
		
		try {
			Object pojo=Class.forName(clazz).newInstance();
			
			if(uniqueCodeArray!=null&&uniqueCodeArray.length!=0){
				getBusinessBean().deleteById(pojo.getClass(), uniqueCodeArray);
			}
		} catch(Exception e){
			PrintWriter out=null;
			try {				
				out=response.getWriter();
				out.println(JsonHelp.getFormFailJson("保存数据失败！"));
				e.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} finally{
				out.close();
			}
		}
		return null;	
	}
	/**
	 * 到处excel表
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward export(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		POIExcel poie=new POIExcel();
		OutputStream os = null;
		Map<String,FilterBean> map=createFilterMap(request);
		String clazz = request.getParameter("clazz");
		clazz=ClassDelegate.clazzMap.get(clazz);
		String name = request.getParameter("name");
		
		try {
			name=new String(name.getBytes("ISO-8859-1"),"UTF-8");
			os = response.getOutputStream();
			response.reset();
			response.setContentType("application/x-msdownload;charset=UTF-8");
			response.setHeader("content-disposition",
			     "attachment; filename=dataexport.xls");
			
			Object pojo=Class.forName(clazz).newInstance();
			
			List list=getBusinessBean()
							.getAllList( pojo,map);
			if(list==null){
				list=new ArrayList<Object>();
			}
			poie.exportExcel(name,os,list,Class.forName(clazz));	
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (ClassNotFoundException e){
			e.printStackTrace();
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try {
				os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
		//return null;
		return mapping.findForward(mapping.getInput());
	}
}
